package com.qujia.station.service.impl;



import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.DateUtils;
import com.qujia.station.domain.NonOilOrder;
import com.qujia.station.domain.StationDeviceManage;

import com.qujia.station.mapper.NonOilOrderMapper;
import com.qujia.station.service.IStationDeviceManageService;
import com.qujia.station.service.NonOilOrderService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * (NonOilOrder)表服务实现类
 *
 * @author makejava
 * @since 2023-08-16 17:46:22
 */
@Service("nonOilOrderService")
public class NonOilOrderServiceImpl implements NonOilOrderService {
    private static final Logger log = LoggerFactory.getLogger(NonOilOrderServiceImpl.class);
    @Resource
    private NonOilOrderMapper nonOilOrderMapper;
    @Autowired
    private IStationDeviceManageService stationDeviceManageService;

    /**
     * 通过ID查询单条数据
     *
     * @param nooId 主键
     * @return 实例对象
     */
    @Override
    public NonOilOrder queryById(Long nooId) {
        return this.nonOilOrderMapper.queryById(nooId);
    }

    /**
     * 分页查询
     *
     * @param nonOilOrder 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<NonOilOrder> queryByPage(NonOilOrder nonOilOrder, PageRequest pageRequest) {
        long total = this.nonOilOrderMapper.count(nonOilOrder);
        return new PageImpl<>(this.nonOilOrderMapper.queryAllByLimit(nonOilOrder, pageRequest), pageRequest, total);
    }

    @Override
    public List<NonOilOrder> query(NonOilOrder nonOilOrder) {
        return nonOilOrderMapper.query(nonOilOrder);
    }

    @Override
    public Map<String, Object> getStatisticsData(NonOilOrder nonOilOrder) {
        return nonOilOrderMapper.getStatisticsData(nonOilOrder);
    }

    @Override
    public Map<String, Object> getTodayStatisticsData(NonOilOrder nonOilOrder) {
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        nonOilOrder.setBeginTime(dateFormat.format(DateUtils.getTodayStartTime()));
        nonOilOrder.setEndTime(dateFormat.format(DateUtils.getTodayEndTime()));
        Map<String, Object> statisticsData = nonOilOrderMapper.getStatisticsData(nonOilOrder);
        if(statisticsData.get("count").equals(0l)){
            statisticsData.put("payableAmountTotal",0);
            statisticsData.put("actuallyAmountTotal",0);
            statisticsData.put("discountAmountTotal",0);
        }
        return statisticsData;
    }

    @Override
    public List<NonOilOrder> queryTodayList(NonOilOrder nonOilOrder) {
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        nonOilOrder.setBeginTime(dateFormat.format(DateUtils.getTodayStartTime()));
        nonOilOrder.setEndTime(dateFormat.format(DateUtils.getTodayEndTime()));
        return nonOilOrderMapper.query(nonOilOrder);
    }

    @Override
    public List<NonOilOrder> queryHistoryList(NonOilOrder nonOilOrder) {
        return nonOilOrderMapper.query(nonOilOrder);
    }

    /**
     * 新增数据
     *
     * @param nonOilOrder 实例对象
     * @return 实例对象
     */
    @Override
    public NonOilOrder insert(NonOilOrder nonOilOrder) {
        this.nonOilOrderMapper.insert(nonOilOrder);
        return nonOilOrder;
    }

    /**
     * 修改数据
     *
     * @param nonOilOrder 实例对象
     * @return 实例对象
     */
    @Override
    public NonOilOrder update(NonOilOrder nonOilOrder) {
        this.nonOilOrderMapper.update(nonOilOrder);
        return this.queryById(nonOilOrder.getNooId());
    }

    /**
     * 通过主键删除数据
     *
     * @param nooId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long nooId) {
        return this.nonOilOrderMapper.deleteById(nooId) > 0;
    }

    @Override
    public int feiePush(Long nooId) {
        NonOilOrder nonOilOrder = new NonOilOrder();
        nonOilOrder.setNooId(nooId);
        List<NonOilOrder> query = query(nonOilOrder);
        if(query.size()!=0){
            nonOilOrder = query.get(0);
        }else{
            return 0;
        }

        log.info("订单信息{}",nonOilOrder);
        StationDeviceManage stationDeviceManage = new StationDeviceManage();
        stationDeviceManage.setStationId(nonOilOrder.getStationId());
        stationDeviceManage.setDeviceType("3");
        List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
        log.info("小票机信息{}",stationDeviceManages);
        if (stationDeviceManages == null || stationDeviceManages.size() <= 0) {
            throw new CustomException("当前站点没有打印机");
        }
        //加油员ID
        //String oilPersonnelId = nonOilOrder.getStaffId();

        StringBuilder content = new StringBuilder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (true) {
            content.append("--------顾客联----补打-----<BR>");
            if (nonOilOrder.getPayableAmount() != null) {
                content.append("<BOLD><B>应付金额：" + nonOilOrder.getPayableAmount() + "元</B></BOLD><BR>");
            }
            if (StringUtils.isNotBlank(nonOilOrder.getOrderCode())) {
                content.append("订单号：" + nonOilOrder.getOrderCode() + "<BR>");
            }

            if (nonOilOrder.getActuallyAmount() != null) {
                content.append("实付金额：" + nonOilOrder.getActuallyAmount() + "<BR>");
            }

            if (nonOilOrder.getDiscountAmount() != null) {
                content.append("优惠金额：" + nonOilOrder.getDiscountAmount() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getMobilePhone())) {

                content.append("手机号：" + nonOilOrder.getMobilePhone().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2") + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getPayType())) {
                if ("wx".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "微信" + "<BR>");
                } else if ("zfb".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "支付宝" + "<BR>");
                } else if ("yl".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "银联" + "<BR>");
                } else if ("xj".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "现金" + "<BR>");
                } else if ("dzk".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "电子卡" + "<BR>");
                } else if ("hyk".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "实体卡" + "<BR>");
                }

            }

            if (nonOilOrder.getCreateTime() != null) {
                content.append("下单时间：" + sdf.format(nonOilOrder.getCreateTime()) + "<BR>");
            }

            if (nonOilOrder.getPayTime() != null) {
                content.append("付款时间：" + sdf.format(nonOilOrder.getPayTime()) + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getCommodityName())) {
                content.append("商品名称：" + nonOilOrder.getCommodityName() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getCommodityCode())) {
                content.append("商品编号：" + nonOilOrder.getCommodityCode() + "<BR>");
            }
            if (nonOilOrder.getRetailPrice() != null) {
                content.append("零售价格：" + nonOilOrder.getRetailPrice() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getSalePrice() + "")) {
                content.append("销售价格：" + nonOilOrder.getSalePrice() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getStationName())) {
                content.append("油站：" + nonOilOrder.getStationName() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getStaffName())) {
                content.append("员工：" + nonOilOrder.getStaffName() + "<BR>");
            }

            content.append("-------------------------<BR>");
            content.append("<BR>");
        }
        if (true) {
            content.append("--------商户联-----补打----<BR>");
            if (nonOilOrder.getPayableAmount() != null) {
                content.append("<BOLD><B>应付金额：" + nonOilOrder.getPayableAmount() + "元</B></BOLD><BR>");
            }
            if (StringUtils.isNotBlank(nonOilOrder.getOrderCode())) {
                content.append("订单号：" + nonOilOrder.getOrderCode() + "<BR>");
            }

            if (nonOilOrder.getActuallyAmount() != null) {
                content.append("实付金额：" + nonOilOrder.getActuallyAmount() + "<BR>");
            }

            if (nonOilOrder.getDiscountAmount() != null) {
                content.append("优惠金额：" + nonOilOrder.getDiscountAmount() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getMobilePhone())) {

                content.append("手机号：" + nonOilOrder.getMobilePhone().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2") + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getPayType())) {
                if ("wx".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "微信" + "<BR>");
                } else if ("zfb".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "支付宝" + "<BR>");
                } else if ("yl".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "银联" + "<BR>");
                } else if ("xj".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "现金" + "<BR>");
                } else if ("dzk".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "电子卡" + "<BR>");
                } else if ("hyk".equals(nonOilOrder.getPayType())) {
                    content.append("支付方式：" + "实体卡" + "<BR>");
                }

            }

            if (nonOilOrder.getCreateTime() != null) {
                content.append("下单时间：" + sdf.format(nonOilOrder.getCreateTime()) + "<BR>");
            }

            if (nonOilOrder.getPayTime() != null) {
                content.append("付款时间：" + sdf.format(nonOilOrder.getPayTime()) + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getCommodityName())) {
                content.append("商品名称：" + nonOilOrder.getCommodityName() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getCommodityCode())) {
                content.append("商品编号：" + nonOilOrder.getCommodityCode() + "<BR>");
            }
            if (nonOilOrder.getRetailPrice() != null) {
                content.append("零售价格：" + nonOilOrder.getRetailPrice() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getSalePrice() + "")) {
                content.append("销售价格：" + nonOilOrder.getSalePrice() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getStationName())) {
                content.append("油站：" + nonOilOrder.getStationName() + "<BR>");
            }

            if (StringUtils.isNotBlank(nonOilOrder.getStaffName())) {
                content.append("员工：" + nonOilOrder.getStaffName() + "<BR>");
            }
            content.append("-------------------------<BR>");
            content.append("<BR>");
        }
        content.append("<BR>");
        content.append("<BR>");


     //   StationDeviceManage stationDeviceManagerRes;
        /*try {
            //筛选绑定了用户的小票机
            List<StationDeviceManage> manageWithUser = new ArrayList<>();
            if(nonOilOrder!=null&&nonOilOrder.getOilPersonnelId()!=null&&!"".equals(nonOilOrder.getOilPersonnelId())){
                manageWithUser = stationDeviceManages.stream().filter(device -> {
                    if(StringUtils.isNotBlank(device.getUserIds())){
                        List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
                        return userIdsList.contains(oilPersonnelId);
                    }
                    return false;
                }).collect(Collectors.toList());
            }
            stationDeviceManagerRes  = CollectionUtils.isNotEmpty(manageWithUser) ? manageWithUser.get(0) : stationDeviceManages.get(0);
            log.info("筛选绑定用户的小票机信息：{}",stationDeviceManagerRes);
        }catch (Exception e){
            stationDeviceManagerRes = stationDeviceManages.get(0);
            log.error(e.getMessage());
        }*/

      /*  String audio = stationDeviceManagerRes.getAudio();
        log.info("自定义语音audio:{}",audio);

        log.info("最终小票机信息：{}",stationDeviceManagerRes);
        String deviceFactory = stationDeviceManagerRes.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
        switch (printEnum){
            case YILIANYUN:

                String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","").replace("<BOLD><B>","");

                String print = YiLianYunPrinterUtil.print(ylyContent, stationDeviceManagerRes, nonOilOrder);
                break;

            case FEIE:

                FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), content.toString());
                break;
            default:
                log.info("没有配置小票机，打印失败");
                break;
//            return AjaxResult.success("打印成功");
        }*/
        return 0;
    }
}
